<template>
    <div class="pageCon">
        <!-- 滚动框 -->
        <div style="position: relative;width: 100%;">
            <div class="noticeLength">{{ noticeList.length }}</div>
            <el-scrollbar height="100px" style="width: 100%;">
                <div class="noticeItem" v-for="item in noticeList" :key="item.id">
                    <div class="title">{{ item.title }}</div>
                    ：
                    <div class="content">{{ item.content }}</div>
                </div>
            </el-scrollbar>
        </div>
        <span style="margin-top: 20px;display: flex;align-items: center;">
            <span style="font-size: 20px;"> {{ userStore.restaurantName }}：</span>
            早餐支持<span style="color: red;">{{ dayEnum[breakfastTime.day] }}-{{ breakfastTime.time }}点</span> 前预定 ||
            午餐支持 <span style="color: red;">{{ dayEnum[lunchTime.day] }}-{{ lunchTime.time }}点</span> 前预定 ||
            晚餐支持<span style="color: red;">{{ dayEnum[dinnerTime.day] }}-{{ dinnerTime.time }}点</span> 前预定
        </span>
        <el-table :data="dateList" style="width: 90%;margin-top: 20px;" @row-click="handleRowClick" border>
            <el-table-column prop="date" label="日期" width="200px"></el-table-column>
            <el-table-column prop="breakfast" label="早餐">
                <template #header>
                    <div>早餐({{ breakfastPrice }})元</div>
                </template>
                <template #default="scope">
                    <span
                        v-if="dateDish[scope.row.date.split(' ')[0]] && dateDish[scope.row.date.split(' ')[0]].breakfast.length">
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.breakfast"
                            size="small" type="primary"
                            v-if="!dateDish[scope.row.date.split(' ')[0]]?.ifUserOrder.breakfast"
                            @click="handleOrder(scope.row.date.split(' ')[0], 'breakfast')">预定</el-button>
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.breakfast"
                            size="small" @click="handleCancel(scope.row.date.split(' ')[0], 'breakfast')" v-else
                            type="danger">取消</el-button>
                        <span v-for="dish in dateDish[scope.row.date.split(' ')[0]].breakfast" :key="dish.id">
                            <span class="dishName">{{ dish.name }}、</span>
                            <!-- 间隔 -->
                        </span>
                    </span>
                    <div v-else>暂无菜品信息</div>
                </template>
            </el-table-column>
            <el-table-column prop="lunch" label="午餐">
                <template #header>
                    <div>午餐({{ lunchPrice }})元</div>
                </template>
                <template #default="scope">
                    <span
                        v-if="dateDish[scope.row.date.split(' ')[0]] && dateDish[scope.row.date.split(' ')[0]].lunch.length">
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.lunch" size="small"
                            type="primary" @click="handleOrder(scope.row.date.split(' ')[0], 'lunch')"
                            v-if="!dateDish[scope.row.date.split(' ')[0]]?.ifUserOrder.lunch">预定</el-button>
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.lunch" size="small"
                            @click="handleCancel(scope.row.date.split(' ')[0], 'lunch')" v-else
                            type="danger">取消</el-button>
                        <span v-for="dish in dateDish[scope.row.date.split(' ')[0]].lunch" :key="dish.id">
                            <span class="dishName">{{ dish.name }}、</span>
                            <!-- 间隔 -->
                        </span>
                    </span>
                    <div v-else>暂无菜品信息</div>
                </template>
            </el-table-column>
            <el-table-column prop="dinner" label="晚餐">
                <template #header>
                    <div>晚餐({{ dinnerPrice }})元</div>
                </template>
                <template #default="scope">
                    <span
                        v-if="dateDish[scope.row.date.split(' ')[0]] && dateDish[scope.row.date.split(' ')[0]].dinner.length">
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.dinner" size="small"
                            type="primary" @click="handleOrder(scope.row.date.split(' ')[0], 'dinner')"
                            v-if="!dateDish[scope.row.date.split(' ')[0]]?.ifUserOrder.dinner">预定</el-button>
                        <el-button :disabled="!dateDish[scope.row.date.split(' ')[0]]?.canOrderTime.dinner" size="small"
                            @click="handleCancel(scope.row.date.split(' ')[0], 'dinner')" v-else
                            type="danger">取消</el-button>
                        <span v-for="dish in dateDish[scope.row.date.split(' ')[0]].dinner" :key="dish.id">
                            <span class="dishName">{{ dish.name }}、</span>
                            <!-- 间隔 -->
                        </span>
                    </span>
                    <div v-else>暂无菜品信息</div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import { Api } from '@/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const today = ref(new Date()) // 获取今天的日期
const endDay = ref(new Date(today.value.getTime() + 30 * 24 * 60 * 60 * 1000)) // 获取今天到7天后的日期
const weekenum = ['日', '一', '二', '三', '四', '五', '六']
const activeDay = ref('') // 当前选中的日期
const dateList = ref([]) // 存储从今天开始往后七天的日期列表
const dateDish = ref({}) // 存储每天的菜品数据
const dayEnum = ref(['前一天', '当天'])
// 获取today到endDay的日期列表
const getDateList = () => {
    const dateListValue = []
    for (let i = 0; i < 31; i++) {
        // yyyy-mm-dd 星期x
        const date = new Date(today.value.getTime() + i * 24 * 60 * 60 * 1000)
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0') // 月份需要补零
        const day = date.getDate().toString().padStart(2, '0') // 日期需要补零
        const week = weekenum[date.getDay()]
        dateListValue.push({ date: `${year}-${month}-${day} 星期${week}` })
    }
    activeDay.value = dateListValue[0].date
    return dateListValue
}

dateList.value = getDateList()
const noticeList = ref([])

let timer = null;
onMounted(() => {
    Api.getDateRangeDish({ firstDay: today.value.toISOString().split('T')[0], lastDay: endDay.value.toISOString().split('T')[0] }).then(res => {
        dateDish.value = res.data
    })

    Api.getNoticeList({ page: 1, pageSize: 10, ifShow: true }).then(res => {
        noticeList.value = res.data
    })

    _getPrice()

    timer = setInterval(() => {

        const currentTime = new Date().getTime()

        console.log(currentTime, breakfastLine.value, lunchLine.value, dinnerLine.value);
        if (currentTime >= breakfastLine.value || currentTime >= lunchLine.value || currentTime >= dinnerLine.value) {
            Api.getDateRangeDish({ firstDay: today.value.toISOString().split('T')[0], lastDay: endDay.value.toISOString().split('T')[0] }).then(res => {
                dateDish.value = res.data
            })

            Api.getNoticeList({ page: 1, pageSize: 10, ifShow: true }).then(res => {
                noticeList.value = res.data
            })

            _getPrice()
        }
    }, 1000 * 60 * 30)
})
onUnmounted(() => {
    clearTimeout(timer)
})

const handleRowClick = (row) => {
    activeDay.value = row.date
    // 可以在这里添加其他处理逻辑
}

const handleOrder = (date, type) => {
    Api.orderDate({ date, type }).then(res => {
        if (res.status == 200) {
            ElMessage.success('预定成功')
            Api.getDateRangeDish({ firstDay: today.value.toISOString().split('T')[0], lastDay: endDay.value.toISOString().split('T')[0] }).then(res => {
                dateDish.value = res.data
            })
        }
    })
}
const handleCancel = (date, type) => {
    Api.cancelDate({ date, type }).then(res => {
        if (res.status == 200) {
            ElMessage.success('取消成功')
            Api.getDateRangeDish({ firstDay: today.value.toISOString().split('T')[0], lastDay: endDay.value.toISOString().split('T')[0] }).then(res => {
                dateDish.value = res.data
            })
        }
    })
}

const breakfastPrice = ref('')
const lunchPrice = ref('')
const dinnerPrice = ref('')
const breakfastTime = reactive({
    day: 0,
    time: 0
})
const lunchTime = reactive({
    day: 0,
    time: 0
})
const dinnerTime = reactive({
    day: 0,
    time: 0
})


const turnTime = (num) => {
    if (num > 0) {
        return { day: '0', time: (24 - num) }
    } else {
        return { day: '1', time: (0 - num) }
    }
}
const turnAnsTime = (obj) => {
    if (obj.day === '0') {
        return 24 - obj.time
    } else {
        return 0 - obj.time
    }
}
const breakfastLine = ref()
const lunchLine = ref()
const dinnerLine = ref()
const restaurantName = ref()

const _getPrice = () => {
    Api.getPrice().then(res => {
        if (res.status === 200) {
            breakfastPrice.value = res.data.breakfast
            lunchPrice.value = res.data.lunch
            dinnerPrice.value = res.data.dinner
            breakfastTime.day = turnTime(res.data.breakfastTime).day
            breakfastTime.time = turnTime(res.data.breakfastTime).time
            lunchTime.day = turnTime(res.data.lunchTime).day
            lunchTime.time = turnTime(res.data.lunchTime).time
            dinnerTime.day = turnTime(res.data.dinnerTime).day
            dinnerTime.time = turnTime(res.data.dinnerTime).time
            breakfastLine.value = new Date(new Date().toISOString().split('T')[0] + ` ${breakfastTime.time < 10 ? '0' + breakfastTime.time : breakfastTime.time}:00:00`).getTime()
            lunchLine.value = new Date(new Date().toISOString().split('T')[0] + ` ${lunchTime.time < 10 ? '0' + lunchTime.time : lunchTime.time}:00:00`).getTime()
            dinnerLine.value = new Date(new Date().toISOString().split('T')[0] + `  ${dinnerTime.time < 10 ? '0' + dinnerTime.time : dinnerTime.time}:00:00`).getTime()
            userStore.restaurantName = res.data.restaurantName
        }
    })
}
</script>

<style scoped lang="scss">
.pageCon {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .noticeLength {
        position: absolute;
        top: 10px;
        right: 20px;
        font-size: 20px;
        color: #333;
        z-index: 999;
        border: 2px solid #333;
        padding: 10px;
        border-radius: 20px;
    }

    .noticeItem {
        box-sizing: border-box;
        padding: 20px;
        height: 100px;
        border-radius: 20px;
        display: flex;
        align-items: center;
        background-color: #FAFCFF;
        width: 100%;

        .title {
            font-size: 20px;
            color: #333;
        }

        .content {
            color: #FFA500;
        }
    }

    .dishCard {
        display: flex;
        align-items: center;
        border: 1px solid #ebeef5;
        padding: 10px;
        box-sizing: border-box;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

        .dishImg {
            width: 150px;
            height: 150px;
            margin: 0 auto;
        }

        .inf {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;
            height: 100px;
            width: 100px;
            margin: 0 auto;

            .dishName {
                font-size: 18px;
                font-weight: 600;
            }

            .dishPrice {
                font-size: 16px;
                color: #ff0000;
            }
        }
    }
}
</style>